#!/usr/bin/python
# -*- coding: utf-8 -*-

#######################################
#                                     #
# script.module.t0mus.common for xbmc #
# author: t0mus                       #
#                                     #
#######################################

""" Module handles various online videos hosting sites."""

import xbmcaddon
import xbmcgui
import xbmcplugin
import urllib, urllib2,re
import t0mus.common.megustavid
import t0mus.common.nextvideo
import t0mus.common.a33
import t0mus.common.putlocker

from t0mus.common.common import open_url, unescape
from BeautifulSoup import BeautifulSoup

from strings import __header_string__
from common_strings import __categories_string__, __search_string__, \
    __unsupported_hosting_string__, __loadingcategories_string__, \
    __movietitle_string__, __loadingmovies_string__

__addon__ = 'plugin.video.xbmcberry'
try:
    __settings__ = xbmcaddon.Addon(id=__addon__)
except:
    __settings__ = None


def create_list_item(
    this_plugin,
    result,
    name,
    host,
    info_labels
    ):
    """ Creates list item."""

    if result != None:
        list_item = xbmcgui.ListItem(name + ' (' + host + ')', iconImage=info_labels['image'])
        list_item.setInfo(type='video', infoLabels=info_labels)
        xbmcplugin.addDirectoryItem(this_plugin, result, list_item)
    else:
        list_item = xbmcgui.ListItem(name + ' (' + host
                + ' - unsupported)')
        list_item.setInfo(type='video', infoLabels=info_labels)
    return list_item

def extract_movie_info(name):
    info_labels = {'title':name, 'image':''}
    try:
        query = name
        result = re.search(r'( \[.*\]$)',query)
        if(result!=None):
            query = query[:-len(result.groups()[0])]
        if(re.search(r' \(\d{4}\)$',query) != None):
            query = query[:-6].strip()
        try:
            query=urllib.quote(query.split('/')[0])
        except:
            pass

        html = urllib2.urlopen('http://www.filmweb.pl/search?q='+query).read()
        soup = BeautifulSoup(html)
        link = soup.find('ul',attrs={'id':'searchFixCheck'}).find('li','searchResult').find('a','searchResultTitle')['href']
        html = urllib2.urlopen('http://filmweb.pl'+link).read() 
        soup = BeautifulSoup(html)
        table = soup.find('div','info-box').find('table')
        gatunek = ""
        premiera = ""
        rezyseria = ""
        scenariusz = ""
        opis = ""
        for tr in table.findAll('tr'):
            field = tr.find('th').string
            if (field == 'gatunek:'):
                gatunek = tr.find('td').a.string
            elif (field == 'premiera:'):
               premiera = tr.find('td').a.span.findNextSibling('span').string
            elif (field == 'produkcja:'):
                produkcja = tr.find('td').a.string
            elif (field == u're\u017cyseria:'):
                rezyseria = tr.find('td').a.string
            elif (field == 'scenariusz:'):
                for a in tr.find('td').findAll('a'):
                    scenariusz += a.string+', '
        opis = soup.find('span','filmDescrBg').string
        if (opis == None):
            opis = ''
        else:
            opis = unescape(opis)
        image = soup.find('a','film_mini').img['src'].split('?')[0]
        ocena = float(soup.find('span', attrs={'property':'v:average'}).string.replace(',','.'))
        castandrole = []
        for li in soup.findAll('li','clear_li'):
            castandrole.append(unescape(li.h3.a.img['alt'])+' | '+li.div.string)
        info_labels = {'title': name, 'genre':gatunek, 'premiered': premiera, 'director':rezyseria, 'writer':scenariusz, 'plot': opis, 'image':image, 'rating': ocena, 'castandrole':castandrole}
    except:
        pass
    return info_labels

def recognize_video_hosting(this_plugin, link, name):
    """ Searches for urls to all known online video hosting sites."""

    dialog = create_progress_dialog()
    html = urllib2.urlopen(link).read()
    soup = BeautifulSoup(html)
    extract_movies_from_soup(this_plugin,soup,dialog,name)

def create_progress_dialog():
    """ Creates progress dialog."""

    dialog = xbmcgui.DialogProgress()
    dialog.create(__header_string__, __loadingmovies_string__)
    dialog.update(0, __loadingmovies_string__)
    return dialog

def extract_movies_from_soup(this_plugin,soup,dialog,name):
    """ Extracts movie links from soup and creates related list items."""

    if ((__settings__ != None) and (__settings__.getSetting('metadata.filmweb')=='true')):
        info = extract_movie_info(name)
    else:
        info = {'title':name, 'image':''}

    list_items = []

    if ((__settings__ == None) or (__settings__.getSetting('hosting.a33')=='true')):
        for url in t0mus.common.a33.extract_urls(soup):
            list_items.append(create_list_item(this_plugin, url, name, 'a33', info))
    dialog.update(25, __loadingmovies_string__)
    if ((__settings__ == None) or (__settings__.getSetting('hosting.megustavid')=='true')):
        for url in t0mus.common.megustavid.extract_urls(soup):
            list_items.append(create_list_item(this_plugin, url, name, 'megustavid', info))
    dialog.update(50, __loadingmovies_string__)
    if ((__settings__ == None) or (__settings__.getSetting('hosting.nextvideo')=='true')):
        for url in t0mus.common.nextvideo.extract_urls(soup):
            list_items.append(create_list_item(this_plugin, url, name, 'nextvideo', info))
    dialog.update(75, __loadingmovies_string__)
    if ((__settings__ == None) or (__settings__.getSetting('hosting.putlocker')=='true')):
        for url in t0mus.common.putlocker.extract_urls(soup):
            list_items.append(create_list_item(this_plugin, url, name, 'putlocker', info))
    dialog.update(100, __loadingmovies_string__)
    dialog.close()
    if (len(list_items)==0):
        xbmcplugin.addDirectoryItem(this_plugin, '', xbmcgui.ListItem(__unsupported_hosting_string__))

